<template>
  <el-container>
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'remove',
            'export',
            'comSearch',
            'columnDisplay',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm ref="formRef" v-if="baTable.form.operate" />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { ref, provide, onMounted, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, DictOperation } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { AssetGateway } from "@/api/backend/index";
import PopupForm from "./popupForm.vue";
import { useRoute, useRouter } from "vue-router";
import { useNavTabs } from "@/store/navTabs";
import { useAssetGateway } from "@/store/backend/Assets/gateway";
import { useDictionary } from "@/store/backend/tool/dictionary";
import TagSearch from "@/components/tagSearch/index.vue";
import Tag from "./components/tag.vue";
import Search from "./components/search.vue";
import { useAssetCabinet } from "@/store/backend/Assets/cabinet";
import { useAssetSite } from "@/store/backend/Assets/site";
import type { FormInstance } from "element-plus";
import { ElNotification } from "element-plus";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const gateway = useAssetGateway();
const dictionary = useDictionary();
const cabinet = useAssetCabinet();
const site = useAssetSite();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + AssetGateway)
      ? (navTabs as any).pageSizeMap.get(route.path + AssetGateway)
      : 10;
  }
  return 10;
};

//初始化字典处理类
const dictOperation = new DictOperation();

//获取字典
const getDictionary = () => {
  //获取站点类型的字典
  dictOperation.getDictionary(site, "sys_site_type", "siteType", "type");
  //获取网关在线状态的字典
  dictOperation.getDictionary(
    gateway,
    "sys_gateway_onlinestatus",
    "onlineStatus",
    "typeOnline"
  );
  //获取网关开关状态的字典
  dictOperation.getDictionary(
    gateway,
    "sys_gateway_switchstatus",
    "switchStatus",
    "typeSwitch"
  );
};
getDictionary();

//获取站点管理中的不同类型值
const getDistrictNum = (val: string) => {
  let len = site.type.length;
  for (let i = 0; i < len; ) {
    if (site.type[i].dictLabel === val) {
      return site.type[i].dictValue - 0;
    } else {
      i++;
    }
  }
};


//新增站点为网关类型数据
const addSite = (addParams: any) => {
  site
    .addSite(addParams)
    .then((res: any) => {
      console.log("新增站点为网关类型数据", res);
    })
    .catch((err: any) => {
      console.log("新增站点为网关类型数据失败", err);
    });
};
//修改站点数据为网关类型数据
const editSite = (editParams: any) => {
  site
    .editSite(editParams)
    .then((res: any) => {
      console.log("修改站点数据为网关类型数据", res);
    })
    .catch((err: any) => {
      console.log("修改站点数据为网关类型数据失败", err);
    });
};
//判断是否是同个站点区域（网关类型
const isSame = (searchName: string, parentName: string, addParams: any) => {
  site
    .getFilterList({
      siteName: searchName,
      siteType: getDistrictNum("网关"),
    })
    .then((res: any) => {
      console.log("判断是否是同个站点区域（网关类型", res);
      if (res.length > 0) {
        let newObj = _.cloneDeep(res[0]);
        if (
          res[0].parentName != parentName &&
          res[0].siteName != addParams.siteName
        ) {
          //数据不同就修改
          newObj.parentName = parentName; //修改父级名称
          newObj.parentId = addParams.parentId; //修改父级Id
          newObj.siteName = addParams.siteName; //修改本级名称
          editSite(newObj);
        } else if (res[0].parentName != parentName) {
          newObj.parentName = parentName; //修改父级名称
          newObj.parentId = addParams.parentId; //修改父级Id
          editSite(newObj);
        } else if (res[0].siteName != addParams.siteName) {
          newObj.siteName = addParams.siteName; //修改本级名称
          editSite(newObj);
        } else {
          console.log("数据相同不修改");
        }
      } else {
        //没有数据直接新增
        addSite(addParams);
      }
    });
};
//获取机柜在站点的id
const getSiteId = (addParams: any, siteName: string, operate: boolean) => {
  site
    .getFilterList({
      siteName: siteName,
      siteType: getDistrictNum("机柜"),
    })
    .then((res: any) => {
      if (res.length > 0) {
        addParams.siteType = getDistrictNum("网关");
        addParams.parentId = res[0].siteId;
        if (operate) {
          //新增方法
          addSite(addParams);
        } else {
          //编辑方法判断网关类型站点数据是否相同
          isSame(gateway.editsiteName, siteName, addParams);
        }
      } else {
        ElNotification({
          type: "warning",
          message: "所选机柜未绑定站点",
        });
      }
    });
};

//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(AssetGateway), //this.api = api菜单管理相关
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("gatewayName"),
        label: "网关名称",
        prop: "gatewayName",
        align: "center",
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("gatewayCode"),
        label: "网关编号",
        prop: "gatewayCode",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("onlineStatus"),
        label: "在线状态",
        prop: "onlineStatus",
        align: "center",
        render: "customRender",
        customRender: markRaw(Tag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("switchStatus"),
        label: "开关状态",
        prop: "switchStatus",
        align: "center",
        render: "customRender",
        customRender: markRaw(Tag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("siteName"),
        label: "所属机柜",
        prop: "siteName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("uplinkMode"),
        label: "上行通讯方式",
        prop: "uplinkMode",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("downlinkMode"),
        label: "下行通讯方式",
        prop: "downlinkMode",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("simCode"),
        label: "SIM卡号",
        prop: "simCode",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("channels"),
        label: "485通道数量",
        prop: "channels",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("gatewayRemark"),
        label: "备注",
        prop: "gatewayRemark",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("createTime"),
        label: "创建时间",
        prop: "createTime",
        align: "center",
        operator: false,
      },
      {
        label: "站点查询",
        align: "center",
        render: "customRender",
        customRender: markRaw(Search),
        operator: false,
      },
      {
        show: operatorShowOff([route.path + "/edit", route.path + "/remove"]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "itemAddButton",
            name: "itemAdd",
            title: "新增",
            text: "",
            type: "primary",
            icon: "iconfont icon-xinzeng",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
  },
  {
    // 默认表单数据(添加)
    defaultItems: {
      siteOrder: 1,
      siteType: 0, //0为地区类型
    },
  },
  {
    onSubmit: ({
      formEl,
      operate,
      items,
    }: {
      formEl: FormInstance | undefined;
      operate: string;
      items: anyObj;
    }) => {
      console.log("表单提交前", formEl, operate, items);
      let newObj = _.cloneDeep(items);
      let addSiteParams = {
        siteName: newObj.gatewayName, //改为网关名称
        orderNum: 1, //顺序默认为1
        parentName: newObj.siteName,
      };
      if (operate == "edit" && newObj.siteName) {
        getSiteId(addSiteParams, newObj.siteName, false);
      } else if (operate == "add" && newObj.siteName) {
        getSiteId(addSiteParams, newObj.siteName, true);
      }
      return true;
    },
  }
);

type IOT = {};
//跳转网关详情页 流量数据
const infoButtonClick = (name: string, row: any) => {
  console.log("row", row);
  gateway.$patch((state) => {
    state.single = row;
  });
  // router.push({ path: "/admin/AssetGateway/iotDetail" });
};

onMounted(() => {
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(AssetGateway);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        //携带主键字段pk
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("gateway", gateway);
provide("dictionary", dictionary);
provide("cabinet", cabinet);
provide("site", site);
provide("dictOperation", dictOperation);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
